package com.matrix.draft.sockettest.groupchatroom.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

public class GroupChatServer {
    // 配置属性
    private ServerProperties properties;
    // 事件选择器们
    private Selector selector;
    // ServerSocketChannel
    private ServerSocketChannel serverSocketChannel;
    // accept事件处理器
    private KeyEventHandler acceptKeyEventHandler ;
    // read事件处理器
    private KeyEventHandler readKeyEventHandler;

    // 构造函数
    public GroupChatServer() {
        try {
            // 初始化各个成员
            properties = new ServerProperties();
            selector = Selector.open();
            acceptKeyEventHandler = new AcceptKeyEventHandler();
            readKeyEventHandler = new ReadKeyEventHandler();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听
    public void listen() {
        try {
            serverSocketChannel.bind(new InetSocketAddress(properties.getHost(), properties.getPort()));
            System.err.println("聊天室服务端已启动在"+properties.getHost()+":"+properties.getPort()+"...");
            while (selector.select() > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        acceptKeyEventHandler.handle(key);
                    } else if (key.isReadable()) {
                        readKeyEventHandler.handle(key);
                    }
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
